import backtrader as bt
import akshare as ak
import pandas as pd
import datetime  #
import os.path  # 路径管理
import sys  # 获取当前运行脚本的路径 (in argv[0])

import baostock as bs
import SimpleMySqlClass as smc


# 1, get stock data from net
def get_stock_data():
    lg = bs.login()
    print("login rsp code=" + lg.error_code)
    print("login rsp msg=" + lg.error_msg)
    rs = bs.query_history_k_data_plus(
        "sh.600000",
        "date,time,code,open,high,low,close,volume,amount,adjustflag",
        start_date="2017-07-01",
        end_date="2017-12-30",
        frequency="60",
        adjustflag="3",
    )
    print("query_history_k_data_plus rsp code" + rs.error_code)
    print("query_history_k_data_plus rsp msg" + rs.error_msg)

    # 打印结果
    data_list = []
    while (rs.error_code == "0") & rs.next():
        data_list.append(rs.get_row_data())
        print(rs.get_row_data())
    result = pd.DataFrame(data_list, columns=rs.fields)
    print(result)
    save_data_to_mysql(result)
    print("end ok")
    # 退出
    bs.logout()


# 2, save data to mysql
def save_data_to_mysql(stock_data_df):
    mysql_obj = get_mysql_handle()
    # date time code open high low close volume amount adjustflag
    # INSERT INTO stocks.t_stock_k_minute_data (id, sd_date, sd_date_time, sd_code, sd_symbol, sd_name, sd_open, sd_high, sd_low, sd_close, sd_volume, sd_amount, sd_adjust_flag, sd_data_type, create_time, update_time)

    for index, row in stock_data_df.iterrows():
        # rs = mysql_obj.execute(insertSql)
        insertSql = """INSERT INTO t_stock_k_minute_data 
            (id, sd_date, sd_date_time, sd_code, sd_open, sd_high, sd_low, sd_close, sd_volume, sd_amount,create_time) 
            VALUES 
            (0, %s, %s, %s, %s,%s,%s, %s,%s, %s,%s) """

        s_data = (
            (
                row["date"],
                row["time"],
                row["code"],
                row["open"],
                row["high"],
                row["low"],
                row["close"],
                row["volume"],
                row["amount"],
                datetime.datetime.now(),
            ),
        )
        print("sql = ", insertSql)
        rs = mysql_obj.executeMany(insertSql, s_data)
        print("rs = ", rs)
    print("-------------------------------")
    read_data_from_mysql(mysql_obj)
    close_mysql_handle(mysql_obj)

    pass


def read_data_from_mysql(mysql_obj):
    tableName = "t_stock_k_minute_data"
    sql = f"select sd_date, sd_code, sd_open, sd_high, sd_low, sd_close, sd_volume, sd_amount from {tableName}"
    rs = mysql_obj.query_sql(sql)
    print("query rs = ", rs)
    pass


def get_mysql_handle():
    mysql_obj = smc.SimpleMySqlClass("127.0.0.1", "stocks", "haojg", "haojg")
    return mysql_obj


def close_mysql_handle(mysql_obj):
    mysql_obj.close()
    pass


# 3, query data from mysql

if __name__ == "__main__":
    get_stock_data()
    print("main")

# 1, get hs300
# 2, get zz500
# 3, get my care
# 4, 我的持仓
# 5，订单表，明细
